#!/usr/bin/env python3
"""
CoordinationEngine依赖问题诊断脚本

专门诊断CoordinationEngine和AgentRegistry的导入和初始化问题
"""

import sys
import traceback
from datetime import datetime

def test_agent_registry_import():
    """测试AgentRegistry导入"""
    try:
        from aiquant.agents import AgentRegistry
        print("✅ AgentRegistry导入成功")
        return True, AgentRegistry
    except Exception as e:
        print(f"❌ AgentRegistry导入失败: {e}")
        traceback.print_exc()
        return False, None

def test_coordination_engine_import():
    """测试CoordinationEngine导入 - 使用正确路径"""
    try:
        from aiquant.coordination import CoordinationEngine
        print("✅ CoordinationEngine导入成功 (正确路径)")
        return True, CoordinationEngine
    except Exception as e:
        print(f"❌ CoordinationEngine导入失败 (正确路径): {e}")
        traceback.print_exc()
        return False, None

def test_coordination_engine_wrong_import():
    """测试CoordinationEngine导入 - 使用错误路径"""
    try:
        from aiquant.core import CoordinationEngine
        print("⚠️  CoordinationEngine导入成功 (错误路径) - 这不应该发生")
        return True, CoordinationEngine
    except Exception as e:
        print(f"✅ CoordinationEngine导入失败 (错误路径) - 这是预期的: {e}")
        return False, None

def test_agent_registry_initialization():
    """测试AgentRegistry初始化"""
    try:
        from aiquant.agents import AgentRegistry
        registry = AgentRegistry()
        print("✅ AgentRegistry初始化成功")
        print(f"   - 智能体数量: {len(registry.agents)}")
        print(f"   - 系统指标: {registry.system_metrics}")
        return True, registry
    except Exception as e:
        print(f"❌ AgentRegistry初始化失败: {e}")
        traceback.print_exc()
        return False, None

def test_coordination_engine_initialization():
    """测试CoordinationEngine初始化"""
    try:
        from aiquant.coordination import CoordinationEngine
        from aiquant.agents import AgentRegistry
        
        # 创建AgentRegistry实例
        registry = AgentRegistry()
        
        # 创建CoordinationEngine实例
        engine = CoordinationEngine(registry)
        print("✅ CoordinationEngine初始化成功")
        print(f"   - 活跃协调数量: {len(engine.active_coordinations)}")
        print(f"   - 协调历史数量: {len(engine.coordination_history)}")
        print(f"   - 配置参数: {engine.config}")
        return True, engine
    except Exception as e:
        print(f"❌ CoordinationEngine初始化失败: {e}")
        traceback.print_exc()
        return False, None

async def test_async_initialization():
    """测试异步初始化"""
    try:
        from aiquant.coordination import CoordinationEngine
        from aiquant.agents import AgentRegistry
        
        # 创建实例
        registry = AgentRegistry()
        engine = CoordinationEngine(registry)
        
        # 异步初始化
        await registry.initialize()
        await engine.initialize()
        
        print("✅ 异步初始化成功")
        return True
    except Exception as e:
        print(f"❌ 异步初始化失败: {e}")
        traceback.print_exc()
        return False

def test_coordination_patterns_import():
    """测试coordination_patterns模块导入"""
    try:
        from aiquant.coordination.coordination_patterns import (
            CoordinationMode, CoordinationPattern, CoordinationContext,
            CoordinationStrategy, select_coordination_mode, get_coordination_strategy
        )
        print("✅ coordination_patterns模块导入成功")
        print(f"   - CoordinationMode: {CoordinationMode}")
        return True
    except Exception as e:
        print(f"❌ coordination_patterns模块导入失败: {e}")
        traceback.print_exc()
        return False

def main():
    """主诊断函数"""
    print("=" * 60)
    print("CoordinationEngine依赖问题诊断")
    print("=" * 60)
    print(f"诊断时间: {datetime.now()}")
    print()
    
    results = {}
    
    # 1. 测试AgentRegistry导入
    print("1. 测试AgentRegistry导入")
    results['agent_registry_import'] = test_agent_registry_import()[0]
    print()
    
    # 2. 测试CoordinationEngine导入 (正确路径)
    print("2. 测试CoordinationEngine导入 (正确路径)")
    results['coordination_engine_import_correct'] = test_coordination_engine_import()[0]
    print()
    
    # 3. 测试CoordinationEngine导入 (错误路径)
    print("3. 测试CoordinationEngine导入 (错误路径)")
    results['coordination_engine_import_wrong'] = test_coordination_engine_wrong_import()[0]
    print()
    
    # 4. 测试coordination_patterns导入
    print("4. 测试coordination_patterns模块导入")
    results['coordination_patterns_import'] = test_coordination_patterns_import()
    print()
    
    # 5. 测试AgentRegistry初始化
    print("5. 测试AgentRegistry初始化")
    results['agent_registry_init'] = test_agent_registry_initialization()[0]
    print()
    
    # 6. 测试CoordinationEngine初始化
    print("6. 测试CoordinationEngine初始化")
    results['coordination_engine_init'] = test_coordination_engine_initialization()[0]
    print()
    
    # 7. 测试异步初始化
    print("7. 测试异步初始化")
    import asyncio
    try:
        results['async_init'] = asyncio.run(test_async_initialization())
    except Exception as e:
        print(f"❌ 异步初始化测试失败: {e}")
        results['async_init'] = False
    print()
    
    # 总结
    print("=" * 60)
    print("诊断结果总结")
    print("=" * 60)
    
    passed = sum(1 for v in results.values() if v)
    total = len(results)
    success_rate = (passed / total) * 100
    
    print(f"总测试数: {total}")
    print(f"通过测试: {passed}")
    print(f"失败测试: {total - passed}")
    print(f"成功率: {success_rate:.1f}%")
    print()
    
    print("详细结果:")
    for test_name, result in results.items():
        status = "✅ 通过" if result else "❌ 失败"
        print(f"  {test_name}: {status}")
    
    print()
    print("=" * 60)
    print("问题分析和建议")
    print("=" * 60)
    
    if not results['coordination_engine_import_correct']:
        print("🔥 关键问题: CoordinationEngine正确路径导入失败")
        print("   建议: 检查aiquant.coordination模块结构")
    
    if results['coordination_engine_import_wrong']:
        print("⚠️  警告: 错误路径导入成功 - 可能存在aiquant.core模块")
        print("   建议: 确认是否存在重复的CoordinationEngine定义")
    
    if not results['agent_registry_import'] or not results['agent_registry_init']:
        print("🔥 关键问题: AgentRegistry导入或初始化失败")
        print("   建议: 检查aiquant.agents模块结构")
    
    if not results['coordination_patterns_import']:
        print("🔥 关键问题: coordination_patterns模块导入失败")
        print("   建议: 检查coordination_patterns.py文件")
    
    if results['coordination_engine_import_correct'] and results['agent_registry_import']:
        if not results['coordination_engine_init']:
            print("🔥 关键问题: CoordinationEngine初始化失败")
            print("   建议: 检查CoordinationEngine构造函数和依赖")
    
    print()
    return success_rate >= 85.0

if __name__ == "__main__":
    try:
        success = main()
        sys.exit(0 if success else 1)
    except Exception as e:
        print(f"诊断脚本执行失败: {e}")
        traceback.print_exc()
        sys.exit(1)